# models.py
from django.db import models
from django.db.models import SmallIntegerField
from django.utils import timezone

from user.models import Team
from utils.common_models import *


# class Supplier(models.Model):
#     name = models.CharField(max_length=255, verbose_name='供应商名字')
#     contact_person = models.CharField(max_length=255, verbose_name='联系人')
#     contact_number = models.CharField(max_length=20, verbose_name='联系电话')
#
#     class Meta:
#         db_table = 'erp_supplier'  # 指定表名
#         verbose_name = '供应商表'  # 后台管理看到的中文
#         verbose_name_plural = verbose_name
#
#     def __str__(self):  # 打印对象，显示的
#         return self.name


class ProductCategory(models.Model):
    category_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name='货品名字')
    parent_category_id = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,
                                           db_constraint=False,
                                           verbose_name='父分类ID')
    description = models.TextField(verbose_name='描述', blank=True, null=True)
    image = ImageField(upload_to='product_images', default='product_images/default.png',
                       verbose_name='后台上传货品分类图片')
    photo = models.CharField(max_length=255, default='product_images/default.png', blank=True, null=True,
                             verbose_name='手机端上传货品分类图片')
    team = ForeignKey(to='user.Team', on_delete=models.SET_NULL, db_constraint=False, related_name='product_categories',
                      null=True,
                      verbose_name='关联的店铺ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    # 其他货品分类相关字段

    class Meta:
        db_table = 'erp_product_category'  # 指定表名
        verbose_name = '货品分类表'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return self.name


class Commodity(models.Model):
    commodity_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name='商品名称')
    category = models.ForeignKey('home.ProductCategory', blank=True, related_name='commodity', verbose_name='分类',
                                 on_delete=models.SET_NULL, db_constraint=False, null=True)
    unit = models.ForeignKey(to='home.Unit', blank=True, related_name='commodity', verbose_name='计量单位',
                             on_delete=models.SET_NULL, db_constraint=False, null=True)
    image = ImageField(upload_to='commodity_images', default='commodity_images/default.png',
                       verbose_name='后台上传商品图片')
    photo = models.CharField(max_length=255, default='commodity_images/default.png',
                             verbose_name='手机端上传商品图片', blank=True, null=True)
    # supplier_id = models.ForeignKey('home.Supplier', on_delete=models.CASCADE, related_name='products',
    #                                 verbose_name='供应商')
    # count = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    description = models.TextField(blank=True, null=True, verbose_name='商品描述')
    team = ForeignKey(to='user.Team', on_delete=models.SET_NULL, db_constraint=False, related_name='commodity',
                      null=True,
                      verbose_name='关联的店铺ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    # price_change_id = models.ForeignKey('home.PriceChangeRecords', blank=True, related_name='products',
    #                                     verbose_name='跌涨幅',
    #                                     on_delete=models.CASCADE)

    class Meta:
        db_table = 'erp_commodity'  # 指定表名
        verbose_name = '商品表'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return self.name


class DishProduct(models.Model):
    dish = models.ForeignKey('Dish', on_delete=models.SET_NULL, db_constraint=False, null=True,
                             related_name='dish_products')
    product = models.ForeignKey('home.Product', on_delete=models.SET_NULL, db_constraint=False, null=True,
                                related_name='dish_products')
    weight = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='重量')
    quantity = models.IntegerField(null=True, blank=True, verbose_name='数量')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'erp_dish_product'
        verbose_name = '菜品对应货品详细表'
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return str(self.dish)


class SalesRecord(models.Model):
    record_id = models.AutoField(primary_key=True, verbose_name='记录ID')
    dish = models.ForeignKey('home.Dish', blank=True, related_name='sales', verbose_name='菜品名称',
                             on_delete=models.SET_NULL, db_constraint=False, null=True)
    sales_date = models.DateField(verbose_name='销售日期', blank=True, null=True)
    dish_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='菜品价格')
    dish_vip_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True,
                                         verbose_name='菜品会员价')
    sales_quantity = models.CharField(max_length=255, verbose_name='销售数量')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'erp_sales_record'  # 指定表名
        verbose_name = '菜品销售记录表'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return str(self.dish)


class Dish(models.Model):
    dish_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name='菜品名字')
    image = models.ImageField(upload_to='dish_images', default='dish_images/default.png',
                              verbose_name='后台上传菜品图片')
    photo = models.CharField(max_length=255, default='dish_images/default.png', verbose_name='手机端上传菜品图片',
                             blank=True, null=True)

    dish_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='菜品价格')
    dish_vip_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True,
                                         verbose_name='菜品会员价')
    category = models.ForeignKey(to='DishCategory', on_delete=models.SET_NULL, db_constraint=False, null=True,
                                 related_name='dish',
                                 verbose_name='菜品分类')
    units = models.ForeignKey(to='Unit', on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True,
                              related_name='dish',
                              verbose_name='计量单位')
    products = models.ManyToManyField(to='home.Product', through='DishProduct', blank=True, related_name='dish',
                                      verbose_name='货品')
    description = models.TextField(verbose_name='菜品描述', blank=True, null=True)
    team = models.ForeignKey(to='user.Team', on_delete=models.SET_NULL, db_constraint=False, related_name='dish',
                             null=True,
                             verbose_name='关联的店铺ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'erp_dish'
        verbose_name = '菜品表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

    def category_detail(self):
        if self.category:
            return {'name': self.category.name, 'id': self.category.category_id}
        else:
            return None

    def units_detail(self):
        if self.units:
            return {'name': self.units.name, 'id': self.units.unit_id}
        else:
            return None

    # def products_list(self):
    #     l = []
    #     for product in self.products.all():
    #         l.append({'name': product.dish})
    #     return l

    def products_list(self):
        # 修改这部分以获取关联表中的相关信息
        dish_products = DishProduct.objects.filter(dish=self)
        products_data = []
        for dish_product in dish_products:
            # print(11111)
            if dish_product.product is not None:
                product_data = {
                    'id': dish_product.product.product_id,
                    'name': dish_product.product.name,
                    'weight': dish_product.weight,
                    'quantity': dish_product.quantity,
                }
                products_data.append(product_data)
        return products_data


class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name='货品名称')
    category = models.ForeignKey('home.ProductCategory', blank=True, related_name='products', verbose_name='分类',
                                 on_delete=models.SET_NULL, db_constraint=False, null=True)
    unit = models.ForeignKey(to='home.Unit', blank=True, related_name='products', verbose_name='计量单位',
                             on_delete=models.SET_NULL, db_constraint=False, null=True)
    image = models.ImageField(upload_to='product_images', default='product_images/default.png',
                              verbose_name='后台上传货品图片')
    photo = models.CharField(max_length=255, default='product_images/default.png', verbose_name='手机端上传货品图片',
                             blank=True, null=True)
    # supplier_id = models.ForeignKey('home.Supplier', on_delete=models.CASCADE, related_name='products',
    #                                 verbose_name='供应商')
    # count = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    description = models.TextField(blank=True, null=True, verbose_name='货品叙述')
    team = ForeignKey(to='user.Team', on_delete=models.SET_NULL, db_constraint=False, related_name='products',
                      null=True,
                      verbose_name='关联的店铺ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间', )

    # def save(self, *args, **kwargs):
    #     if not self.created_at:  # 如果创建时间为空，则使用后端自动生成的时间
    #         self.created_at = timezone.now()
    #     super().save(*args, **kwargs)

    # price_change_id = models.ForeignKey('home.PriceChangeRecords', blank=True, related_name='products',
    #                                     verbose_name='跌涨幅',
    #                                     on_delete=models.CASCADE)

    class Meta:
        db_table = 'erp_product'  # 指定表名
        verbose_name = '货品表'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的

        return str(self.name)


class Inventory(models.Model):
    record_id = models.AutoField(primary_key=True, verbose_name='进货记录唯一标识符')
    product = models.ForeignKey('home.Product', blank=True, related_name='inventory', verbose_name='货品名称',
                                on_delete=models.SET_NULL, db_constraint=False, null=True)
    product_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='货品价格')
    product_cost_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True,
                                             verbose_name='货品成本价')
    stock_in_time = models.DateTimeField(verbose_name='货品入库时间', blank=True, null=True)
    quantity = models.CharField(max_length=255, verbose_name='货品入库数量', default=0, blank=True, null=True)
    weight = models.CharField(max_length=255, verbose_name='货品入库重量', default=0, blank=True, null=True)
    before_weight = models.CharField(max_length=255, verbose_name='货品填入重量', default=0, blank=True, null=True)
    # 新增体积字段
    volume = models.CharField(max_length=255, null=True, blank=True, verbose_name='货品体积')
    # 新增按用户id过滤库存
    user_id = models.CharField(max_length=255, null=True, blank=True, verbose_name='用户id')
    stock_out_time = models.DateTimeField(verbose_name='货品出库时间', blank=True, null=True)
    stock_out_quantity = models.CharField(max_length=255, verbose_name='货品出库数量/重量', blank=True, null=True)
    current_stock = models.CharField(max_length=255, verbose_name='现有库存量(重量换算成g,数量换算成个)', blank=True,
                                     null=True)
    procurement = models.TextField(blank=True, null=True, verbose_name='采购叙述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'erp_inventory'  # 指定表名
        verbose_name = '进销存表（库存表）'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return str(self.product.name)


class DishCategory(models.Model):
    category_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name='菜品分类名字')
    parent_category = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, db_constraint=False,
                                        verbose_name='父分类ID')
    description = models.TextField(verbose_name='描述', blank=True, null=True)
    image = ImageField(upload_to='dish_images', default='dish_images/default.png', verbose_name='后台上传菜品分类图片')
    photo = models.CharField(max_length=255, default='dish_images/default.png', verbose_name='手机端上传菜品分类图片',
                             blank=True, null=True)
    team = ForeignKey(to='user.Team', on_delete=models.SET_NULL, db_constraint=False, related_name='dish_categories',
                      null=True,
                      verbose_name='关联的店铺ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'erp_dish_category'  # 指定表名
        verbose_name = '菜品分类表'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return self.name


class Unit(models.Model):
    type = (
        (1, '数量单位'),
        (2, '称重单位'),
    )
    unit_id = models.AutoField(primary_key=True, verbose_name='单位ID')
    name = models.CharField(max_length=50, verbose_name='单位名称')
    unit_type = SmallIntegerField(choices=type, default=1, verbose_name='单位类型')
    conversion_relation = models.CharField(max_length=255, verbose_name='换算关系')  # 根据实际情况选择适当的字段类型
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_dish_unit = models.BooleanField(default=False, verbose_name='是否菜品单位')  # 新添加的字段

    class Meta:
        db_table = 'erp_unit'  # 指定表名
        verbose_name = '单位表'  # 后台管理看到的中文
        verbose_name_plural = verbose_name

    def __str__(self):  # 打印对象，显示的
        return self.name
